package com.tma.demo;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.tma.demo.custom.BookAdapter;
import com.tma.demo.custom.LoadBookTask;
import com.tma.demo.utils.ImageLoader;
import com.tma.demo.xml.Book;

public class CustomListViewActivity extends Activity implements OnItemClickListener {
    public static final String TAG = "CustomListViewActivity";
    private ListView mListView;
    private BookAdapter mAdapter;
    private LoadBookTask mAsynTask;
    private ImageLoader mImageLoader;

    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_list_view);

        mImageLoader = new ImageLoader(this);
        mAdapter = new BookAdapter(this, mImageLoader);
        mListView = (ListView) findViewById(R.id.lv_book);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(this);

        mAsynTask = (LoadBookTask) getLastNonConfigurationInstance();
        if (mAsynTask != null) {
            mAsynTask.attach(this);
            mAsynTask.resumeProgressDialog();
        } else {
            mAsynTask = new LoadBookTask(this);
            mAsynTask.execute();
        }
    }

    @Override
    protected void onDestroy() {
        if (mAsynTask != null) {
            mAsynTask.hideProgressDialog();
        }
        mImageLoader.clearCache();
        super.onDestroy();
    }

    @Override
    @Deprecated
    public Object onRetainNonConfigurationInstance() {
        return mAsynTask;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_custom_list_view, menu);
        return true;
    }

    public void onItemClick(AdapterView<?> adapterView, View target, int position, long id) {
        Book book = (Book) mAdapter.getItem(position);
        Log.i(TAG, "Select: " + book);
        Toast.makeText(this, book.getTitle(), Toast.LENGTH_SHORT).show();
    }

    public void appendBook(Book book) {
        if (book != null) {
            mAdapter.getData().add(book);
            mAdapter.notifyDataSetChanged();
        }
    }

    public void appendBooks(List<Book> books) {
        if (books != null) {
            mAdapter.getData().addAll(books);
            mAdapter.notifyDataSetChanged();
        }
    }

    public void displayBooks(List<Book> books) {
        if (books != null) {
            mAdapter.getData().clear();
            mAdapter.getData().addAll(books);
            mAdapter.notifyDataSetChanged();
        }
    }

    public void clearBooks() {
        mAdapter.getData().clear();
        mAdapter.notifyDataSetChanged();
    }
}
